namespace LicenseApp.Client;

/// <summary>
/// 授权信息助手 - 提供格式化的授权信息获取方法
/// </summary>
public static class LicenseInfoHelper
{
    /// <summary>
    /// 获取完整的授权信息摘要
    /// </summary>
    /// <returns>格式化的授权信息字符串</returns>
    public static string GetLicenseSummary()
    {
        try
        {
            var licenseInfo = LicenseManager.GetLicenseInfo();
            var statusInfo = LicenseManager.GetCurrentStatus();

            if (licenseInfo == null)
            {
                // 🎯 返回详细的错误信息而不是通用的"未找到"
                return $"❌ {statusInfo.Message}";
            }

            var summary = new System.Text.StringBuilder();
            
            // 授权状态
            summary.AppendLine($"授权状态: {GetStatusText(statusInfo.Status)}");

            // 设备信息
            summary.AppendLine($"授权设备: {licenseInfo.AgvCount} 台AGV");

            // 时间信息
            summary.AppendLine($"生效日期: {licenseInfo.StartDate:yyyy年MM月dd日}");
            summary.AppendLine($"到期日期: {licenseInfo.EndDate:yyyy年MM月dd日}");
            summary.AppendLine($"授权天数: {licenseInfo.Days} 天");

            // 剩余时间
            if (statusInfo.Status != LicenseStatus.Expired)
            {
                summary.AppendLine($"剩余天数: {statusInfo.RemainingDays} 天");
            }

            // 宽限期信息
            if (statusInfo.GracePeriod != null)
            {
                var graceHours = (int)statusInfo.GracePeriod.RemainingGraceTime.TotalHours;
                summary.AppendLine($"宽限期剩余: {graceHours} 小时");
            }
            
            // 检查时间
            summary.AppendLine($"🔍 检查时间: {statusInfo.CheckTime:yyyy-MM-dd HH:mm:ss}");

            return summary.ToString().TrimEnd();
        }
        catch (Exception ex)
        {
            return $"❌ 获取授权信息失败: {ex.Message}";
        }
    }

    /// <summary>
    /// 获取简洁的授权信息
    /// </summary>
    /// <returns>简洁的授权信息字符串</returns>
    public static string GetLicenseBrief()
    {
        try
        {
            var licenseInfo = LicenseManager.GetLicenseInfo();
            var statusInfo = LicenseManager.GetCurrentStatus();

            if (licenseInfo == null)
            {
                // 🎯 根据具体的错误类型返回相应的简洁信息
                return GetBriefErrorMessage(statusInfo.Message);
            }

            string statusText = GetStatusText(statusInfo.Status);

            if (statusInfo.Status == LicenseStatus.Valid || statusInfo.Status == LicenseStatus.ExpiringSoon)
            {
                return $"{statusText} | {licenseInfo.AgvCount}台AGV | 剩余{statusInfo.RemainingDays}天";
            }
            else
            {
                return $"{statusText} | {licenseInfo.AgvCount}台AGV";
            }
        }
        catch
        {
            return "授权信息获取失败";
        }
    }

    /// <summary>
    /// 获取设备授权信息
    /// </summary>
    /// <returns>设备授权信息</returns>
    public static DeviceAuthInfo GetDeviceAuthInfo()
    {
        try
        {
            var licenseInfo = LicenseManager.GetLicenseInfo();
            var statusInfo = LicenseManager.GetCurrentStatus();

            return new DeviceAuthInfo
            {
                IsAuthorized = licenseInfo != null && statusInfo.Status != LicenseStatus.Expired,
                MaxAgvCount = licenseInfo?.AgvCount ?? 0,
                Status = statusInfo.Status,
                RemainingDays = statusInfo.RemainingDays,
                ExpiryDate = licenseInfo?.EndDate ?? DateTime.MinValue,
                StatusMessage = GetStatusText(statusInfo.Status)
            };
        }
        catch
        {
            return new DeviceAuthInfo
            {
                IsAuthorized = false,
                MaxAgvCount = 0,
                Status = LicenseStatus.Expired,
                RemainingDays = 0,
                ExpiryDate = DateTime.MinValue,
                StatusMessage = "获取失败"
            };
        }
    }

    /// <summary>
    /// 获取详细的授权信息对象
    /// </summary>
    /// <returns>详细授权信息</returns>
    public static DetailedLicenseInfo GetDetailedLicenseInfo()
    {
        try
        {
            var licenseInfo = LicenseManager.GetLicenseInfo();
            var statusInfo = LicenseManager.GetCurrentStatus();

            return new DetailedLicenseInfo
            {
                // 基础信息
                HasLicense = licenseInfo != null,
                AgvCount = licenseInfo?.AgvCount ?? 0,
                StartDate = licenseInfo?.StartDate ?? DateTime.MinValue,
                EndDate = licenseInfo?.EndDate ?? DateTime.MinValue,
                TotalDays = licenseInfo?.Days ?? 0,
                
                // 状态信息
                Status = statusInfo.Status,
                StatusText = GetStatusText(statusInfo.Status),
                IsActive = licenseInfo?.IsActive ?? false,
                RemainingDays = statusInfo.RemainingDays,
                IsExpiringSoon = statusInfo.Status == LicenseStatus.ExpiringSoon,
                
                // 时间信息
                CheckTime = statusInfo.CheckTime,
                
                // 宽限期信息
                IsInGracePeriod = statusInfo.Status == LicenseStatus.ExpiredGracePeriod,
                GracePeriodInfo = statusInfo.GracePeriod,
                
                // 格式化信息
                FormattedSummary = GetLicenseSummary(),
                FormattedBrief = GetLicenseBrief()
            };
        }
        catch (Exception ex)
        {
            return new DetailedLicenseInfo
            {
                HasLicense = false,
                StatusText = $"获取失败: {ex.Message}",
                FormattedSummary = $"❌ 获取授权信息失败: {ex.Message}",
                FormattedBrief = "获取失败"
            };
        }
    }

    /// <summary>
    /// 获取状态文本
    /// </summary>
    private static string GetStatusText(LicenseStatus status)
    {
        return status switch
        {
            LicenseStatus.Valid => "授权有效",
            LicenseStatus.ExpiringSoon => "即将到期",
            LicenseStatus.ExpiredGracePeriod => "过期宽限期",
            LicenseStatus.Expired => "授权过期",
            _ => "状态未知"
        };
    }

    /// <summary>
    /// 根据错误信息获取简洁的错误描述
    /// </summary>
    private static string GetBriefErrorMessage(string errorMessage)
    {
        if (errorMessage.Contains("回拨时间") || errorMessage.Contains("时间回拨") ||
            errorMessage.Contains("停滞") || errorMessage.Contains("系统时间未超过"))
        {
            return "时间验证失败";
        }
        else if (errorMessage.Contains("格式错误") || errorMessage.Contains("签名验证失败"))
        {
            return "授权码无效";
        }
        else if (errorMessage.Contains("已过期"))
        {
            return "授权已过期";
        }
        else if (errorMessage.Contains("未找到授权码文件"))
        {
            return "未找到授权";
        }
        else if (errorMessage.Contains("尚未生效"))
        {
            return "授权未生效";
        }
        else
        {
            return "未授权";
        }
    }

    /// <summary>
    /// 获取用于显示的授权信息表格
    /// </summary>
    /// <returns>表格格式的授权信息</returns>
    public static string GetLicenseTable()
    {
        try
        {
            var licenseInfo = LicenseManager.GetLicenseInfo();
            var statusInfo = LicenseManager.GetCurrentStatus();

            if (licenseInfo == null)
            {
                return "┌─────────────────┐\n│   未找到授权    │\n└─────────────────┘";
            }

            var table = new System.Text.StringBuilder();
            table.AppendLine("┌─────────────────────────────────────┐");
            table.AppendLine("│              授权信息               │");
            table.AppendLine("├─────────────────────────────────────┤");
            table.AppendLine($"│ 状态: {GetStatusText(statusInfo.Status),-25} │");
            table.AppendLine($"│ 设备: {licenseInfo.AgvCount,-3} 台AGV{"",-20} │");
            table.AppendLine($"│ 生效: {licenseInfo.StartDate:yyyy-MM-dd}{"",17} │");
            table.AppendLine($"│ 到期: {licenseInfo.EndDate:yyyy-MM-dd}{"",17} │");
            
            if (statusInfo.Status != LicenseStatus.Expired)
            {
                table.AppendLine($"│ 剩余: {statusInfo.RemainingDays,-3} 天{"",21} │");
            }
            
            if (statusInfo.GracePeriod != null)
            {
                var graceHours = (int)statusInfo.GracePeriod.RemainingGraceTime.TotalHours;
                table.AppendLine($"│ 宽限: {graceHours,-3} 小时{"",19} │");
            }
            
            table.AppendLine("└─────────────────────────────────────┘");

            return table.ToString();
        }
        catch (Exception ex)
        {
            return $"┌─────────────────┐\n│  获取信息失败   │\n│ {ex.Message,-15} │\n└─────────────────┘";
        }
    }

    /// <summary>
    /// 获取JSON格式的授权信息
    /// </summary>
    /// <returns>JSON字符串</returns>
    public static string GetLicenseJson()
    {
        try
        {
            var detailedInfo = GetDetailedLicenseInfo();
            
            var json = new
            {
                hasLicense = detailedInfo.HasLicense,
                agvCount = detailedInfo.AgvCount,
                status = detailedInfo.Status.ToString(),
                statusText = detailedInfo.StatusText,
                isActive = detailedInfo.IsActive,
                startDate = detailedInfo.StartDate.ToString("yyyy-MM-dd"),
                endDate = detailedInfo.EndDate.ToString("yyyy-MM-dd"),
                totalDays = detailedInfo.TotalDays,
                remainingDays = detailedInfo.RemainingDays,
                isExpiringSoon = detailedInfo.IsExpiringSoon,
                isInGracePeriod = detailedInfo.IsInGracePeriod,
                checkTime = detailedInfo.CheckTime.ToString("yyyy-MM-dd HH:mm:ss")
            };

            return System.Text.Json.JsonSerializer.Serialize(json, new System.Text.Json.JsonSerializerOptions 
            { 
                WriteIndented = true 
            });
        }
        catch (Exception ex)
        {
            return $"{{\"error\": \"{ex.Message}\"}}";
        }
    }
}

/// <summary>
/// 设备授权信息
/// </summary>
public class DeviceAuthInfo
{
    public bool IsAuthorized { get; set; }
    public int MaxAgvCount { get; set; }
    public LicenseStatus Status { get; set; }
    public int RemainingDays { get; set; }
    public DateTime ExpiryDate { get; set; }
    public string StatusMessage { get; set; } = "";
}

/// <summary>
/// 详细授权信息
/// </summary>
public class DetailedLicenseInfo
{
    // 基础信息
    public bool HasLicense { get; set; }
    public int AgvCount { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public int TotalDays { get; set; }
    
    // 状态信息
    public LicenseStatus Status { get; set; }
    public string StatusText { get; set; } = "";
    public bool IsActive { get; set; }
    public int RemainingDays { get; set; }
    public bool IsExpiringSoon { get; set; }
    
    // 时间信息
    public DateTime CheckTime { get; set; }
    
    // 宽限期信息
    public bool IsInGracePeriod { get; set; }
    public GracePeriodInfo? GracePeriodInfo { get; set; }
    
    // 格式化信息
    public string FormattedSummary { get; set; } = "";
    public string FormattedBrief { get; set; } = "";
}
